package com.gzw.scm.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.Toolbar;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.WXAdapter;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.bean.JgInfo;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/5/2.
 */

public class WXZZXActivity extends BaseActivity {
    private Context mContext;
    private Toolbar toolbar;
    private ProgressDialog mProgressDialog;
    private TextView tv_name;
    private GridView gv_bw;
    private Button btn_sure;
    private WXAdapter wxAdapter;
    private List<JgInfo> ls_jg;
    private Logger log;


    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_zzxwx);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tv_name = (TextView) findViewById(R.id.tv_name);
        gv_bw = (GridView) findViewById(R.id.gv);
        btn_sure = (Button) findViewById(R.id.btn_sure);

        //初始化 log
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("周转箱维修");
        setSupportActionBar(toolbar);
        ls_jg = new ArrayList<>();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(v -> finish());
        btn_sure.setOnClickListener(v -> setData());
    }

    /**
     * 扫描结果
     */
    @Override
    protected String scanRelust(String code) {
        if(code.contains("该二维码不是周转箱")){
            T.showShort(mContext,"该二维码不是周转箱");
        }else {
            tv_name.setText(code);
            GetPJTask getPJTask = new GetPJTask();
            getPJTask.execute(code);
        }
        return code;
    }

    ;

    /**
     * 上传的数据
     **/
    public void setData() {
        if (isNull(tv_name)) {
            T.showShort(mContext, "请先扫码要异维修的周转箱二维码");
            return;
        }
        List<JgInfo> lsbh = new ArrayList<>();
        for (int i = 0; i <ls_jg.size(); i++){
            if (wxAdapter.getIsSelected().get(i)) {
                if(ls_jg.get(i).getNumber()==null){
                    T.showShort(mContext,"请输入所需配件数量");
                }else if(Integer.valueOf(ls_jg.get(i).getNumber())>Integer.valueOf(ls_jg.get(i).getNum())){
                    T.showShort(mContext,"输入数量不能大于原有数量");
                }else{
                    lsbh.add(ls_jg.get(i));
                }
            }
        }
        if (lsbh.size() == 0) {
            T.showShort(mContext, "请选择维修所需配件");
        } else {
            String str = new String();
            for (int i = 0; i < lsbh.size(); i++) {
                str = str + "," + lsbh.get(i).getId() + "," + lsbh.get(i).getNumber();
            }
            str = str.substring(1, str.length());
            String code = tv_name.getText().toString().trim();
            SendTask sendTask = new SendTask();
            sendTask.execute(code,str);
        }
    }

    /**
     * 上传的数据请求
     * */

    public class SendTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {

            String json="tboxsNo="+params[0]+"&did="+MyApplication.getUserInfo().getDid()+"&belongid="+String.valueOf(MyApplication.getUserInfo().getBelongId())
                    +"&type=4&userid="+MyApplication.getUserInfo().getId()+"&parts="+params[1];
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("branchOperation.do","PDABranch"),json);
//            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do","PDABranch"), json);

        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();

            try {
            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
                if(result.contains("系统异常")){
                    showAlertDialog("网络异常");
                    return;
                }

            if(result.contains("true")){
                showAlertDialog("上报维修成功");
                tv_name.setText("");
                ls_jg.clear();
                wxAdapter = new WXAdapter(mContext,ls_jg);
                gv_bw.setAdapter(wxAdapter);
            }else if(result.contains("false")){
                showAlertDialog("上报维修失败");
            }
            }catch (Exception e) {
                log.info("PDABranch:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    /**
     * 获取配件的请求
     * */

    public class GetPJTask extends AsyncTask<String, Void, String> {

        protected String doInBackground(String... params) {
            String json ="getparts=true&tboxsNo="+params[0]+"&did="+MyApplication.getUserInfo().getDid();
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("branchOperation.do","PDABranch"), json);
        }

        @Override
        protected void onPostExecute(final String result) {
            try {

            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }

            if(result.contains("系统异常")){
                showAlertDialog("网络异常");
                return;
            }
            JigInfo jigInfo = JsonUtil.getPerson(result, JigInfo.class);
            if (jigInfo.getResult().equals("false")) {
                T.showShort(mContext, jigInfo.getValue());
            } else {
                String jgStr = jigInfo.getValue();
                String[] str_Array = jgStr.split(",");
                List<String> ls_id = new ArrayList<>();
                List<String> ls_mc = new ArrayList<>();
                List<String> ls_num = new ArrayList<>();


                for (int i = 0; i < str_Array.length; i++) {
                    if (even(i) == 0) {
                        ls_id.add(str_Array[i]);
                    } else if (even(i) == 1) {
                        ls_mc.add(str_Array[i]);
                    } else if (even(i) == 2) {
                        ls_num.add(str_Array[i]);
                    }
                }
                ls_jg.clear();
                for (int i = 0; i < ls_id.size(); i++) {
                    JgInfo jgInfo = new JgInfo();
                    jgInfo.setId(ls_id.get(i));
                    jgInfo.setMc(ls_mc.get(i));
                    jgInfo.setNum(ls_num.get(i));
                    ls_jg.add(jgInfo);
                }
                wxAdapter = new WXAdapter(mContext,ls_jg);
                gv_bw.setAdapter(wxAdapter);

            }
            }catch (Exception e) {
                log.info("PDABranch:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    /**判断奇偶*/
    private int even( int n )
    {
        int num = 0;
        if(n%3==0) {
            num = 0;
        } else if(n%3==1){
            num = 1;
        } else if(n%3==2){
            num = 2;
        }
        return num;
    }

    class JigInfo{
        private String result;
        private String value;

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

}
